const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const path = require('path');
const axios = require('axios');
const app = express();
const PORT = 4001;
// 解析post请求
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }))
// 设置资源跨域共享
app.use(cors())

// 设置静态资源路径
app.use(express.static(path.resolve(__dirname, 'public')))
app.use(express.static(path.resolve(__dirname, 'dist')))
app.get('/test', async (req, res) => {
	res.send({ code: 200, msg: "测试接口" })
})

// 获取高德地图开放平台的key
// 注册申请地址：https://lbs.amap.com/?ref=https://console.amap.com/dev/key/app
const key = '';

// 查询城市编码 （传递中文地址：例如：广州，北京，漠河）
const searchCityCode = async (keywords) => {
	let address = keywords;
	let city = keywords;
	let url = `https://restapi.amap.com/v3/geocode/geo?address=${address}&output=json&key=${key}&city=${city}`;
	return axios.get(url).then(response => response.data);
}

// 查询城市天气
const searchCityWeather = async (city) => {
	const url = 'https://restapi.amap.com/v3/weather/weatherInfo?parameters'
	// 调用第三方接口
	return axios.get(url, { params: { key, city: city } }).then(response => response.data);
}

// 根据城市名称获取天气数据
// 请求地址： /weather
// 请求方式： get
// 请求参数： city  
// 响应数据格式： json
// 示例： http://localhost:4001/weather?city=北京
app.get('/weather', async (req, res) => {
	let city = req.query.city;
	console.log("city:",city)
	if (city) {
		// 首先查询城市编码
		let adcode;
		await searchCityCode(city).then(data => {
			// status: "1" 表示成功
			// status: "0" 表示失败
			if (data.status == "1") {
				let geocodes = data.geocodes
				if (geocodes) {
					adcode = geocodes[0].adcode
				}
			}
			else {
				res.send({
					code: -1,
					msg: data.status
				})
			}
		})
		// 再根据城市编码获取当前位置的天气信息
		await searchCityWeather(adcode).then(data => {
			if (data.status == "1") {
				res.send({
					code: 200,
					msg: "查询天气成功",
					result: data
				})
			}
			else {
				res.send({
					code: -1,
					msg: data.status
				})
			}
		})
	}
	else {
		res.send({ code: -1, msg: "缺少参数" })
	}
})


// 根据城市名称获取天气数据
// 请求地址： /weather
// 请求方式： post
// 请求参数： city  
// 响应数据格式： json
// 示例： http://localhost:4001/weather?city=北京
app.post('/weather', async (req, res) => {
	let city = req.body.city;
	// console.log("city:",city)
	if (city) {
		// 首先查询城市编码
		let adcode;
		await searchCityCode(city).then(data => {
			// status: "1" 表示成功
			// status: "0" 表示失败
			if (data.status == "1") {
				let geocodes = data.geocodes
				if (geocodes) {
					adcode = geocodes[0].adcode
				}
			}
			else {
				res.send({
					code: -1,
					msg: data.status
				})
			}
		})
		// 再根据城市编码获取当前位置的天气信息
		await searchCityWeather(adcode).then(data => {
			if (data.status == "1") {
				res.send({
					code: 200,
					msg: "查询天气成功",
					result: data
				})
			}
			else {
				res.send({
					code: -1,
					msg: data.status
				})
			}
		})
	}
	else {
		res.send({ code: -1, msg: "缺少参数" })
	}
})

app.listen(PORT, () => {
	console.log("NODEJS Web服务启动成功了...")
	console.log("http://localhost:" + PORT)
})

